import json
from typing import Dict, List, Any

#转换 Postman Collection 格式
class PostmanConverter:
    @staticmethod
    def v2_to_v1(collection_v2: Dict[str, Any]) -> Dict[str, Any]:
        collection_v1 = {
            "id": collection_v2.get("info", {}).get("_postman_id", ""),
            "name": collection_v2.get("info", {}).get("name", ""),
            "description": collection_v2.get("info", {}).get("description", ""),
            "order": [],
            "folders": [],
            "requests": []
        }

        def convert_request(request: Dict[str, Any]) -> Dict[str, Any]:
            url = request.get("request", {}).get("url", {})
            if isinstance(url, str):
                raw_url = url
            else:
                raw_url = url.get("raw", "")

            return {
                "id": request.get("id", ""),
                "name": request.get("name", ""),
                "description": request.get("description", ""),
                "method": request.get("request", {}).get("method", "GET"),
                "headers": request.get("request", {}).get("header", ""),
                "url": raw_url,
                "dataMode": "raw",
                "data": request.get("request", {}).get("body", {}).get("raw", ""),
                "collectionId": collection_v1["id"]
            }

        def process_items(items: List[Dict[str, Any]], parent_id: str = None):
            for item in items:
                if "request" in item:
                    # 这是一个请求
                    converted_request = convert_request(item)
                    collection_v1["requests"].append(converted_request)
                    if parent_id is None:
                        collection_v1["order"].append(converted_request["id"])
                elif "item" in item:
                    # 这是一个文件夹
                    folder = {
                        "id": item.get("id", ""),
                        "name": item.get("name", ""),
                        "description": item.get("description", ""),
                        "order": [],
                        "collection_id": collection_v1["id"]
                    }
                    collection_v1["folders"].append(folder)
                    process_items(item["item"], folder["id"])

        # 开始处理所有项目
        if "item" in collection_v2:
            process_items(collection_v2["item"])

        return collection_v1

    @staticmethod
    def convert_file(input_path: str, output_path: str):
        """转换Postman Collection文件"""
        try:
            # 读取V2格式文件
            with open(input_path, 'r', encoding='utf-8') as f:
                collection_v2 = json.load(f)

            # 转换为V1格式
            collection_v1 = PostmanConverter.v2_to_v1(collection_v2)

            # 保存V1格式文件
            with open(output_path, 'w', encoding='utf-8') as f:
                json.dump(collection_v1, f, indent=2, ensure_ascii=False)

            return True
        except Exception as e:
            print(f"转换失败: {str(e)}")
            return False

# 使用示例
if __name__ == "__main__":
    input_file = "C:\\Users\\yy010u\\Desktop\\v2.json"
    output_file = "C:\\Users\\yy010u\\Desktop\\collection_v1.json"
    
    if PostmanConverter.convert_file(input_file, output_file):
        print(f"转换成功！结果已保存到 {output_file}")
    else:
        print("转换失败！")